package com.ayoka.ui.course.detail;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.ayoka.Constant;
import com.ayoka.R;
import com.ayoka.base.AppContext;
import com.ayoka.base.BaseActivity;
import com.ayoka.bean.CourseBean;
import com.ayoka.bean.CourseBean.InteractiveQuestionBean;
import com.ayoka.bean.MusicFileBean;
import com.ayoka.database.DBManager;
import com.ayoka.databinding.ActivityCourseDetailBinding;
import com.ayoka.mvp.CourseMVP.CourseModel.ResponseCourseDetailBean;
import com.ayoka.mvp.CourseMVP.CoursePresenter;
import com.ayoka.mvp.CourseMVP.ICourseView;
import com.ayoka.ui.training.TrainingGroupActivity;
import com.ayoka.utils.CourseEvent;
import com.danikula.videocache.HttpProxyCacheServer;
import com.jcp.baselibrary.model.ToolBarOptions;
import com.jcp.baselibrary.permission.MPermission;
import com.jcp.baselibrary.utils.MyLogger;
import com.jincp.image.load.ImageLoaderProxy;
import com.jzvd.JZMediaIjkplayer;
import com.jzvd.SimpleJZMediaPlayerListener;

import java.io.File;

import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;

/**
 * =========================================================
 * @ProjectName: 
 * @ClassName: CourseDetailActivity
 * @Description: 
 * @Author: jincp
 * @CreateDate: 2019/3/27 10:59
 * =========================================================
 */
public class CourseDetailActivity extends BaseActivity<ActivityCourseDetailBinding, CoursePresenter> implements ICourseView {

    private String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

    public static void start(Activity activity, long courseId) {
        Intent intent = new Intent(activity, CourseDetailActivity.class);
        intent.putExtra("CourseId", courseId);
        activity.startActivity(intent);
    }

    private long courseId;
    private ResponseCourseDetailBean courseDetailBean;
    private CourseBean courseBean;

    private boolean isComplete;

    @Override
    protected void configIntentValue() {
        courseId = getIntent().getLongExtra("CourseId", 0);
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_course_detail;
    }

    @Override
    protected void initViews() {
        mDataBinding.ivAssignment.setOnClickListener(this);
        mDataBinding.ivCollection.setOnClickListener(this);

        mDataBinding.ivCourseText.setOnClickListener(this);
        mDataBinding.ivCourseQuestion.setOnClickListener(this);
        mDataBinding.ivCourseMeditation.setOnClickListener(this);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        ToolBarOptions options = new ToolBarOptions(R.string.course_detail);
        setCustomToolBar(mDataBinding.customToolbar.toolbar, options);

        mPresenter.getCourseDetailData(courseId);
    }

    @Override
    protected CoursePresenter getPresenter() {
        return new CoursePresenter(this);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (courseBean == null) {
            showToast(getString(R.string.get_data_failure));
            finish();
            return;
        }
        if (view == mDataBinding.ivAssignment || view == mDataBinding.ivCourseMeditation) {
            TrainingGroupActivity.start(CourseDetailActivity.this, courseBean.ID, 0);
        }
        if (view == mDataBinding.ivCourseText) {
            mPresenter.showCourseTextDialog(getSupportFragmentManager(), courseBean);
        }
        if (view == mDataBinding.ivCourseQuestion) {
            mPresenter.showCourseQuestionDialog(this, getSupportFragmentManager(), courseBean);
        }
        if (view == mDataBinding.ivCollection) {
            if (courseBean.IsFavorited == 1) {
                mPresenter.cancelCollectionCourse(courseBean.ID);
            } else {
                mPresenter.collectionCourse(courseBean.ID);
            }
        }
    }

    @Override
    public void configCourseDetailData(final ResponseCourseDetailBean courseDetailBean) {
        if (courseDetailBean == null || courseDetailBean.course == null) return;
        this.courseDetailBean = courseDetailBean;
        this.courseBean = courseDetailBean.course;

        // 设置收藏按钮
        if (courseBean.IsFavorited == 1) {
            mDataBinding.ivCollection.setImageResource(R.mipmap.icon_course_collected);
        } else {
            mDataBinding.ivCollection.setImageResource(R.mipmap.icon_course_uncollected);
        }

        // 设置文件播放类型和播放器
        JZVideoPlayer.setVideoImageDisplayType(JZVideoPlayer.VIDEO_IMAGE_DISPLAY_TYPE_FILL_SCROP);
        JZVideoPlayer.setMediaInterface(new JZMediaIjkplayer());
        // 使用代理保存文件
        HttpProxyCacheServer proxy = AppContext.proxy;
        String proxyUrl = proxy.getProxyUrl(courseBean.VideoUrl);
        // 获取文件MD5的加密文件名称
        final String mediaFileName = mPresenter.getFileNameGenerator().generate(courseBean.VideoUrl);
        // 查询数据库中课程文件信息
        MusicFileBean musicFileBean = DBManager.getInstance().queryMusic(mediaFileName);
        if (musicFileBean == null) {
            // 数据库中添加课程文件信息
            DBManager.getInstance().saveMusic(new MusicFileBean(mediaFileName));
            mDataBinding.videoPlayer.setUp(proxyUrl, JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, courseBean.Title);
        } else {
            File file = new File(Constant.CourseVideoDirectory, mediaFileName);
            if (file.exists() && musicFileBean.size == file.length()) {
                mDataBinding.videoPlayer.setUp(file.getAbsolutePath(), JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, courseBean.Title);
            } else {
                mDataBinding.videoPlayer.setUp(proxyUrl, JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, courseBean.Title);
            }
        }
        // 设置缩略图
        ImageLoaderProxy.getInstance().displayImage(courseBean.ImgUrl, mDataBinding.videoPlayer.thumbImageView);
        // 设置下载按钮点击事件
        mDataBinding.videoPlayer.setOnDownLoadClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (MPermission.hasPermissions(CourseDetailActivity.this, permissions)) {
                    mPresenter.downloadCourse(courseBean.VideoUrl);
                } else {
                    MPermission.with(CourseDetailActivity.this).permissions(permissions).request();
                }
            }
        });
        // 设置播放事件监听
        mDataBinding.videoPlayer.setJZMediaPlayerListener(new SimpleJZMediaPlayerListener() {

            @Override
            public void onProgressUpdate(int progress, long position, long duration) {
                MyLogger.d(TAG, "onProgressUpdate");
                if (courseBean != null && courseBean.InteractiveQuestions != null && !courseBean.InteractiveQuestions.isEmpty()) {
                    InteractiveQuestionBean courseMessageOption = courseBean.InteractiveQuestions.get(0);
                    if (position / 1000 >= courseMessageOption.OnShowSecond && position / 1000 <= courseMessageOption.OnHideSecond) {
                        courseBean.InteractiveQuestions.remove(0);
                        mPresenter.showMessageOptionDialog(getSupportFragmentManager(), courseMessageOption, courseMessageOption.OnHideSecond - courseMessageOption.OnShowSecond);
                    }
                    if (position / 1000 > courseMessageOption.OnHideSecond) {
                        courseBean.InteractiveQuestions.remove(0);
                    }
                }
                if (!isComplete && position >= duration - 15000) {
                    isComplete = true;
                    mPresenter.UpdateCourseCompletedStatus(courseBean.ID, courseDetailBean.record_id);
                }
            }

            @Override
            public void onStateAutoComplete() {
                CourseCompletedActivity.start(CourseDetailActivity.this, courseId);
                finish();
            }
        });
    }

    @Override
    public void onUpdateCourseCompletedStatusSuccess() {
        // 配置作业练习
        courseBean.CourseCompletedStatus = 1;
        CourseEvent.getInstance().notifyOCourseChanged();
    }

    @Override
    public void onMessageOptionSelected(long questionId, int optionIndex) {
        mPresenter.AddCourseInteractiveAnswer(courseDetailBean.record_id, courseBean.ID, questionId, optionIndex);
    }

    @Override
    public void onCancelCollectionCourseSuccess() {
        courseBean.IsFavorited = 0;
        showToast("已取消收藏！");
        mDataBinding.ivCollection.setImageResource(R.mipmap.icon_course_uncollected);
    }

    @Override
    public void onCollectionCourseSuccess() {
        courseBean.IsFavorited = 1;
        showToast("收藏成功！");
        mDataBinding.ivCollection.setImageResource(R.mipmap.icon_course_collected);
    }

    @Override
    public void onDownloadSuccess(String filePath) {
        showToast("下载完成");
//        if (mDataBinding.videoPlayer.currentState == JZVideoPlayer.CURRENT_STATE_PLAYING) {
//            mDataBinding.videoPlayer.startLocalPlay(filePath);
//        } else {
//            mDataBinding.videoPlayer.setUp(filePath, JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, courseBean.Title);
//        }
    }

    @Override
    public void onDownloadStart() {
        JZVideoPlayer.goOnPlayOnPause();
        showToast("开始下载");
    }

    @Override
    public void onCourseTextDialogDismiss() {
    }

    @Override
    protected void onPause() {
        super.onPause();
        JZVideoPlayer.goOnPlayOnPause();
    }


    @Override
    public void onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        // 释放当前播放器
        mDataBinding.videoPlayer.setJZMediaPlayerListener(null);
        // 释放所有
        JZVideoPlayer.releaseAllVideos();
        super.onDestroy();
    }
}
